package com.ruoyi.xixi.service;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.xixi.domain.User;
import com.ruoyi.xixi.repository.UserMessageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    private static final String DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions";
    private static final String API_KEY = "sk-1b313ae9880a4d54b866be88f9e8b545";
@Autowired
private UserMessageRepository userMessageRepository;
    public String getMessage(User user) {
        JSONObject requestBody = new JSONObject();
        requestBody.put("model", "deepseek-chat");

// 构造 messages 数组
        JSONArray messages = new JSONArray();
        JSONObject message = new JSONObject();
        message.put("role", "user");
        message.put("content", "你现在有一个名为hank4P营销案例数据库对"+user.getUserQuestion()+"进行1000字以内评价只生成结果不要带有我现在的话，以后我问你的话都要以相同的格式回答我前缀加上hankAI生成资产：");
        messages.add(message);

        requestBody.put("messages", messages);
        requestBody.put("temperature", 0.7);
        requestBody.put("max_tokens", 1000);
        // 发送 POST 请求
        String response = HttpUtil.createPost(DEEPSEEK_API_URL)
                .header("Authorization", "Bearer " + API_KEY)
                .header("Content-Type", "application/json")
                .body(requestBody.toString())
                .execute().body();

// 处理响应
//        System.out.println("API 响应: " + response);
        JSONObject jsonResponse = JSONObject.parseObject(response);
        String generatedText = jsonResponse.getJSONArray("choices")
                .getJSONObject(0)
                .getJSONObject("message")
                .getString("content");
//        响应存储
        user.setUserAnswer(generatedText);
        userMessageRepository.save(user);
        return  generatedText;
    }
}
